package com.megaspacevr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.megaspacevr.entity.AnonymousUsers;
import com.megaspacevr.entity.vo.DeviceInfoVO;
import com.megaspacevr.entity.vo.PageVO;
import com.megaspacevr.entity.vo.UserIdentityVO;
import com.megaspacevr.mapper.AnonymousUsersMapper;
import com.megaspacevr.service.AnonymousUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 匿名用户表-用于设备识别 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-06-17
 */
@Slf4j
@Service
public class AnonymousUsersServiceImpl extends ServiceImpl<AnonymousUsersMapper, AnonymousUsers> implements AnonymousUsersService {

    @Override
    public UserIdentityVO identifyOrCreateUser(DeviceInfoVO deviceInfoVO, HttpServletRequest request) {
        UserIdentityVO userIdentityVO = new UserIdentityVO();
        
        // 优先通过设备指纹查找用户
        AnonymousUsers existingUser = null;
        if (StringUtils.hasText(deviceInfoVO.getDeviceFingerprint())) {
            existingUser = findByDeviceFingerprint(deviceInfoVO.getDeviceFingerprint());
        }
        
        if (existingUser != null) {
            // 用户已存在，更新访问信息
            updateVisitInfo(existingUser.getId());
            
            // 重新查询获取最新数据
            existingUser = getById(existingUser.getId());
            
            userIdentityVO.setUserToken(existingUser.getUserToken());
            userIdentityVO.setIsNewUser(false);
            userIdentityVO.setVisitCount(existingUser.getVisitCount());
            userIdentityVO.setBookingCount(existingUser.getBookingCount());
        } else {
            // 创建新用户
            AnonymousUsers newUser = createNewUser(deviceInfoVO, request);
            
            userIdentityVO.setUserToken(newUser.getUserToken());
            userIdentityVO.setIsNewUser(true);
            userIdentityVO.setVisitCount(1);
            userIdentityVO.setBookingCount(0);
        }
        
        return userIdentityVO;
    }

    @Override
    public AnonymousUsers findByDeviceFingerprint(String deviceFingerprint) {
        if (!StringUtils.hasText(deviceFingerprint)) {
            return null;
        }
        
        QueryWrapper<AnonymousUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_fingerprint", deviceFingerprint);
        return getOne(queryWrapper);
    }

    @Override
    public AnonymousUsers findByUserToken(String userToken) {
        if (!StringUtils.hasText(userToken)) {
            return null;
        }
        
        QueryWrapper<AnonymousUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_token", userToken);
        return getOne(queryWrapper);
    }

    @Override
    public void updateVisitInfo(Long userId) {
        AnonymousUsers user = getById(userId);
        if (user != null) {
            user.setLastVisitTime(LocalDateTime.now());
            user.setVisitCount(user.getVisitCount() + 1);
            updateById(user);
        }
    }

    @Override
    public PageVO<AnonymousUsers> getAnonymousUsersForAdmin(Integer pageNum, Integer pageSize, String searchText, 
                                                           String startDate, String endDate, String sortType) {
        log.info("管理员查询匿名用户列表 - 页码: {}, 页大小: {}, 搜索: {}", pageNum, pageSize, searchText);
        
        PageVO<AnonymousUsers> pageVO = new PageVO<>();
        PageHelper.startPage(pageNum, pageSize);
        
        List<AnonymousUsers> users = baseMapper.getAnonymousUsersForAdmin(searchText, startDate, endDate, sortType);
        Page<AnonymousUsers> page = (Page<AnonymousUsers>) users;
        pageVO.setTotal(page.getTotal());
        pageVO.setItems(page.getResult());
        
        log.info("管理员匿名用户列表查询完成，共 {} 条记录", page.getTotal());
        return pageVO;
    }

    @Override
    public List<AnonymousUsers> getAnonymousUsersListForAdmin(String searchText, String startDate, String endDate, String sortType) {
        log.info("管理员导出匿名用户列表 - 搜索: {}", searchText);
        
        List<AnonymousUsers> users = baseMapper.getAnonymousUsersForAdmin(searchText, startDate, endDate, sortType);
        log.info("管理员导出匿名用户列表完成，共 {} 条记录", users.size());
        return users;
    }

    /**
     * 创建新用户
     */
    private AnonymousUsers createNewUser(DeviceInfoVO deviceInfoVO, HttpServletRequest request) {
        AnonymousUsers newUser = new AnonymousUsers();
        
        // 生成唯一的用户Token
        String userToken = generateUserToken();
        newUser.setUserToken(userToken);
        
        // 设置设备信息
        newUser.setDeviceFingerprint(deviceInfoVO.getDeviceFingerprint());
        
        // 获取真实IP地址
        String realIp = getRealIpAddress(request);
        newUser.setIpAddress(realIp);
        
        // 设置User-Agent
        String userAgent = request.getHeader("User-Agent");
        newUser.setUserAgent(userAgent);
        
        // 设置时间信息
        LocalDateTime now = LocalDateTime.now();
        newUser.setFirstVisitTime(now);
        newUser.setLastVisitTime(now);
        
        // 初始化计数器
        newUser.setVisitCount(1);
        newUser.setBookingCount(0);
        
        // 设置创建和更新时间
        newUser.setCreatedAt(now);
        newUser.setUpdatedAt(now);
        
        // 保存到数据库
        save(newUser);
        
        return newUser;
    }

    /**
     * 生成用户Token
     */
    private String generateUserToken() {
        return "USR_" + UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }

    /**
     * 获取真实IP地址
     */
    private String getRealIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 处理多个IP的情况，取第一个非unknown的有效IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip;
    }
}
